package com.iweb.servlet;

import com.alibaba.fastjson.JSON;
import com.iweb.entity.ReturnData;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

/**
 * @author jay
 * @date 2021/9/13
 * @description
 */
@WebServlet(name = "uploadServlet", value = {"/fileUpload.do"})
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ReturnData returnData = new ReturnData();
        // 判断表单中是否包含文件
        boolean multipartContent = ServletFileUpload.isMultipartContent(req);
        if (multipartContent) {
            // 1. 实例化FieldItemFactory对象
            FileItemFactory factory = new DiskFileItemFactory();
            // 2. 创建ServletFileUpload实例
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
            // 3. 获取表单中的每个元素
            try {
                List<FileItem> fileItems = servletFileUpload.parseRequest(req);
                // 4.解析表单中的每个元素
                for (FileItem fileItem : fileItems) {
                    // 普通表单元素
                    if (fileItem.isFormField()) {
                        // 获取value值
                        System.out.println(fileItem.getString());
                    } else {
                        // 表单文件元素
                        String fileItemName = fileItem.getName();
                        if (fileItemName != null && !"".equals(fileItemName)) {
                            // 改名
                            fileItemName = UUID.randomUUID().toString().replaceAll("-", "") + fileItemName;
                            // 进行保存操作
                            // 定义要保存的路径
                            // 设置上传的文件的路径
                            String uploadPath = req.getServletContext().getRealPath("upload/");
                            //创建文件夹
                            File upload = new File(uploadPath);
                            if (!upload.exists()) {
                                upload.mkdirs();
                            }

                            // TODO:判断文件类型，大小等 限制jpg格式，大小为1m
                            File tempFile = new File(fileItemName);
                            // 判断文件大小
                            if (fileItem.getSize() > 1024 * 1024) {
                                // 设置错误信息
                                returnData.setCode("A0703");
                                returnData.setErrorMessage("图片大小不能超过1MB");
                                output(returnData, resp);
                                return;
                            }
                            // 判断类型  xx.jpg
                            int index = tempFile.getName().lastIndexOf(".") + 1;
                            if (!"jpg".equals(tempFile.getName().substring(index))) {
                                // 设置错误信息 A0701
                                returnData.setCode("A0701");
                                returnData.setErrorMessage("图片类型必须为jpg格式");
                                output(returnData, resp);
                                return;
                            }
                            File saveFile = new File(uploadPath, tempFile.getName());
                            // 满足要求，进行保存
                            fileItem.write(saveFile);
                            returnData.success(saveFile.getName());
                            output(returnData, resp);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                returnData.setCode("A0500");
                returnData.setErrorMessage("图片类型必须为jpg格式");
                output(returnData, resp);
            }
        }
    }

    private void output(ReturnData returnData, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        String jsonString = JSON.toJSONString(returnData);
        PrintWriter writer = resp.getWriter();
        writer.print(jsonString);
        writer.close();
    }
}
